package com.shu.realm;

import com.shu.constant.UserConstants;
import com.shu.dao.UserMapper;
import com.shu.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

public class CustomRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(CustomRealm.class);
    @Autowired
    private UserMapper userMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        //获取用户名
        String username= (String) upToken.getUsername();
        String password ="";
        if (upToken.getPassword() != null)
        {
            password = new String(upToken.getPassword());
        }
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            logger.info("==========用户名或密码为空=========");
            throw new UnknownAccountException("用户名或密码为空");
        }
        if(username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH){
            logger.info("==========用户名长度不正确=========");
            throw new UnknownAccountException("用户名长度不正确");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            logger.info("==========密码长度不正确=========");
            throw new IncorrectCredentialsException("密码长度不正确");
        }

        //通过用户名获取凭证
        User user=userMapper.queryUserByUserName(username);
        if (StringUtils.isEmpty(user)){
            logger.info("==========用户不存在=========");
            throw new UnknownAccountException("用户不存在");
        }

        if(!user.getPassword().equals(encryptPassword(password, user.getSalt()))){
            logger.info("==========密码错误=========");
            throw new IncorrectCredentialsException("密码错误");
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,user.getPassword(),"custcomRealm");
        //加盐
        authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(user.getSalt()));
        return authenticationInfo;
    }

    public String encryptPassword(String password, String salt)
    {
        return new Md5Hash(password,salt).toString();
    }
}
